import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import '../utils/adapt.dart';
import '../event_bus.dart';
import '../utils/request.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class VideoPlayer extends StatefulWidget {
  var arguments;
  VideoPlayer({Key? key, this.arguments}) : super(key: key);

  @override
  _VideoPlayerState createState() =>
      _VideoPlayerState(arguments: this.arguments);
}

class _VideoPlayerState extends State<VideoPlayer> {
  var arguments;
  _VideoPlayerState({this.arguments});
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  var hasVideo = false;
  void initVideo(src) {
    _videoPlayerController = VideoPlayerController.network(src);
    // _videoPlayerController.initialize();
    _chewieController = ChewieController(
      videoPlayerController: _videoPlayerController,
      aspectRatio: 5 / 3,
      autoPlay: true,
      looping: false,
    );
    this.setState(() {
      hasVideo = true;
    });
    EasyLoading.dismiss();
  }

  void getVideoSrc(id) async {
    EasyLoading.show(status: 'loading...');
    var res = await getHttp("/mv/url?id=$id&r=720");
    var videoSrc = res['data']['url'];
    if (videoSrc == null) {
      Navigator.pop(context);
      EasyLoading.dismiss();
    } else {
      var httpsUrl = videoSrc.replaceAll('http', 'https');
      initVideo(httpsUrl);
      eventbus.fire(new changeAudioState(false)); // 把音频暂停
    }
  }

  @override
  void initState() {
    super.initState();
    getVideoSrc(arguments['vid']);
  }

  @override
  void dispose() {
    super.dispose();
    _videoPlayerController.dispose();
    _chewieController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('视频播放'),
      ),
      body: ListView(
        children: [
          AspectRatio(
            aspectRatio: 5 / 3,
            child: Container(
              child: hasVideo != false
                  ? Chewie(controller: _chewieController)
                  : Image.network(
                      arguments['cover'] + '?param=500y300',
                      fit: BoxFit.cover,
                    ),
            ),
          ),
          ListTile(
            title: Text(arguments['name'] != null ? arguments['name'] : ''),
          ),
          ListTile(
            title: Text(
                arguments['artistName'] != null ? arguments['artistName'] : ''),
          ),
          ListTile(
            title: Text(arguments['desc'] != null ? arguments['desc'] : ''),
          )
        ],
      ),
    );
  }
}
